package com.atguigu.pratice2;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*synchronized 和 lock 的区别
1.synchronized是关键字，而lock是工具类
2.synchronized 是独占锁+非公平锁  ReentrantLock是独占锁+非公平锁(默认)+公平锁同时具备
3.synchronized 是必须要等前一个进程使用完资源，后边的进程才能使用该资源
lock 具有，超时等待，中途退出取消机制，
4.两者都是可重入锁
 */
//门票资源类
    public class demo1 {
        public static void main(String[] args) {
            Ticket ticket = new Ticket();
            //三个售票员卖50张票，表示有三个线程
            // 线程 操作 资源类

            new Thread(() -> {for (int i = 0; i < 50; i++) ticket.sale();}, "A").start();
            new Thread(() -> {for (int i = 0; i < 50; i++) ticket.sale();}, "B").start();
            new Thread(() -> {for (int i = 0; i < 50; i++) ticket.sale();}, "C").start();

        }
    }

class Ticket {
    //默认属性50张票
    private int num = 50;
    //方法卖出
    Lock lock = new ReentrantLock(true);

    public void sale() {
        lock.lock();
        try {
            if (num > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出:" + num-- + "张票，还剩:" + num + "张票");
            }

        } finally {
            lock.unlock();
        }
    }
}
